<template>
    <div class="main">
        <div class="topTitle">{{ props.title }}</div>
        <div class="form_content">
            <NScrollbar>
                <NSpin :show="spinShow">
                    <div class="content">
                        <div class="content_cen">
                            <NForm ref="formRef" require-mark-placement="left" label-placement="left" :rules="rules"
                                :label-width="110" :model="formValue" style="width: 350rem;" label-align="right">

                                <NFormItem label="库房名称:" path="warehouseName">
                                    <NInput placeholder="请输入库房名称" v-model:value="formValue.warehouseName" clearable
                                        class="commonWidth" :allow-input="noSideSpace" />
                                </NFormItem>

                                <NFormItem label="上级库房:" path="parentId">
                                    <div style="display: flex;width: 100%;flex-direction: column;">
                                        <NTreeSelect :options="dropDetopList" placeholder="请选择上级库房" clearable
                                            class="commonWidth" v-model:value="formValue.parentId" key-field="id"
                                            label-field="warehouseName" children-field="childList" check-strategy="all"
                                            :on-update:value="changeTree" show-path />
                                        <div v-if="!formValue.parentId"
                                            style="color: red;font-size: 14px;padding: 3px;">
                                            如不选，默认为第一层</div>
                                    </div>
                                </NFormItem>

                                <NFormItem label="备注:" path="remark">
                                    <NInput placeholder="请输入备注" style="min-height: 120rem" type="textarea"
                                        v-model:value="formValue.remark" clearable class="commonWidth"
                                        :allow-input="noSideSpace" />
                                </NFormItem>
                            </NForm>
                        </div>
                    </div>
                </NSpin>
            </NScrollbar>
        </div>
    </div>
    <FixedAction>
        <div style="display: flex">
            <NSpace justify="start" style="flex: 0 0 44%">
                <NButton style="width: 78px; color: #5fb17f" ghost @click="goBack">
                    <template #icon>
                        <img :src="VBackImg" style="width: 25rem; height: 25rem" />
                    </template>
                    返回
                </NButton>
            </NSpace>

            <NSpace justify="center">
                <NButton type="primary" @click="confirm()" :loading="loading" style="width: 115px;">保存</NButton>
            </NSpace>
        </div>
    </FixedAction>

    <NModal :auto-focus="false" v-model:show="contentVisible" @close="contentVisible = false">
        <VDialogContent @close="contentVisible = false" @submit="submit" title="保存提示">
            <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
                您确定要保存吗？
            </div>
        </VDialogContent>
    </NModal>
</template>
<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue'
import {
    NSpace, NForm, NInput, NFormItem, NButton, NScrollbar, NModal, useMessage, NSpin, NTreeSelect,
    type FormInst
} from 'naive-ui'
import router from '@/router'
import { useTagStore } from '@/stores/layout'
import FixedAction from '@/components/FixedAction.vue'
import { sendRequest } from '@/utils/api'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import VBackImg from '@/assets/images/back.png'

const tags = useTagStore().tags
const props = defineProps({
    title: { type: String, default: () => '库房新增' },
    id: { type: [Number, String], default: () => null },
    flat: { default: () => false }
})
const message = useMessage()

// 表单数据
const formValue = reactive<Record<string, any>>({
    warehouseName: null, //库房名称
    parentId: null, //上级库房id
    parentName: null, //上级库房name
    warehouseLevel: null, //上级库房级别
    remark: null //备注
})
// 表单数据效验
const rules = {
    warehouseName: {
        required: true,
        trigger: ['input', 'blur'],
        validator: (_: any, value: any) => {
            if (!value) return new Error('请输入库房名称')
            if (value?.length > 100) return new Error('库房名称字数不得超过100')
            return true
        }
    },
    remark: {
        required: false,
        trigger: ['input', 'blur'],
        validator: (_: any, value: any) => {
            if (value?.length > 500) return new Error('备注字数不得超过500')
            return true
        }
    }
}
// 上级库房选择
const changeTree = (id: any, info: any) => {
    formValue.parentId = id
    formValue.parentName = info?.warehouseName
    formValue.warehouseLevel = info?.warehouseLevel
}
// 限制前后空格
const noSideSpace = (value: string) => !value.startsWith(' ') && !value.endsWith(' ')
// 返回
const goBack = () => {
    const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)
    tags.splice(index, 1)
    if (tags.length == 0) router.push({ path: '/OA/Workbench/UserDesktop' })
    else history.back()
}
// 确定
const loading = ref(false)
const formRef = ref<FormInst | null>(null)
const confirm = () => {
    formRef.value?.validate(async (err) => {
        if (err) return (contentVisible.value = false)
        contentVisible.value = true
    })
}
// 提交
const contentVisible = ref(false)
const submit = async () => {
    if ((props.id && props.flat) || (!props.id && !props.flat)) {
        loading.value = true
        contentVisible.value = false
        const [error, res] = await sendRequest({
            module: 'assetsManagement',
            api: 'detopManagementAdd',
            override: {
                data: formValue
            }
        })
        loading.value = false
        if (error) return message.error(error.message)
        if (res.code !== 0) return message.error(res.msg)
        message.success('保存成功')
    } else {
        loading.value = true
        contentVisible.value = false
        const [error, res] = await sendRequest({
            module: 'assetsManagement',
            api: 'detopManagementUpdate',
            override: {
                data: {
                    ...formValue,
                    id: props.id
                }
            }
        })
        loading.value = false
        if (error) return message.error(error.message)
        if (res.code !== 0) return message.error(res.msg)
        message.success('保存成功')
    }
    goBack()
}
// 获取修改详情
const spinShow: any = ref(false)
const getAttendanceInfo = async () => {
    spinShow.value = true
    const [error, res] = await sendRequest({
        module: 'assetsManagement',
        api: 'detopManagementInfo',
        uri: {
            id: props.id
        }
    })
    if (error) return message.error(error.message)
    if (res.code !== 0) return message.error(res.msg)
    spinShow.value = false
    Object.keys(formValue).map((it: any) => formValue[it] = res.data[it])
}
// 获取上级库房
const dropDetopList = ref([])
const getDropDetopList = async () => {
    const [error, res] = await sendRequest({
        module: 'assetsManagement',
        api: 'dropDetopList',
        override: {
            params: {
                id: props.id
            }
        }
    })
    if (error) return message.error(error.message)
    if (res.code !== 0) return message.error(res.msg)
    dropDetopList.value = res.data
}

watch(
    () => props.id,
    async () => {
        if (props.title == '库房编辑' && props.id) getAttendanceInfo()
    },
    { deep: true, immediate: true }
)

onMounted(() => {
    getDropDetopList()
})
</script>
<style scoped lang="scss">
@mixin CommonFont {
    font-size: 16rem;
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    color: rgba(0, 0, 0, 0.85);
}

.commonWidth {
    width: 240rem;
}

.main {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
    overflow: hidden;

    .topTitle {
        width: 100%;
        border-bottom: 1px solid #fff;
        padding: 15rem 20rem;
        margin-bottom: 20rem;
        @include CommonFont;
    }

    .form_content {
        width: 100%;
        height: 100%;
        padding: 0 20rem 0rem;

        .content {
            display: flex;
            flex-wrap: wrap;
            height: 100%;
            padding: 20rem 0 180rem;
            background-color: #ebeceb;
        }
    }
}

.content_cen {
    display: flex;
    flex-direction: column;
    margin-left: 35%;
}

.content::-webkit-scrollbar {
    display: none;
}

:deep(.n-spin-container) {
    width: 100%;
    height: 100%;
}

:deep(.n-scrollbar-container) {
    width: 100%;
    height: 100%;
}

:deep(.n-scrollbar-content) {
    width: 100%;
    height: 100%;
}

:deep(.n-spin-content) {
    width: 100%;
    height: 100%;
}
</style>